const query = require("../sql/db")
const { selectSimpleWhere } = require("../sql/common")
const {
  pageLimit,
  getKeysSql,
  getValuesSql,
  getKeyMapValue,
} = require("../auth/auth")
const { date_type } = require("../auth/global")

const methods = {
  // 新增商品
  addGoods: (req, res) => {
    const body = req.body
    const { name, description, price, discount_price, number, status } = body
    // 查询商品名是否重复
    selectSimpleWhere("t_goods", { field: "name", value: name }).then(
      (result) => {
        if (result.length) {
          res.fail("商品名重复")
        } else {
          const params = {
            name,
            description,
            price,
            discount_price,
            number,
            status,
          }
          const keys = getKeysSql(params)
          const values = getValuesSql(params)
          const sql = `insert into t_goods (${keys}, create_time, update_time) values (${values}, now(), now())`
          query(sql, (err) => {
            if (err) {
              res.fail("新增失败", { data: err })
            } else {
              res.success()
            }
          })
        }
      }
    )
  },
  // 编辑商品
  editGoods: (req, res) => {
    const body = req.body
    const { name, description, price, discount_price, number, status, id } =
      body
    const params = {
      name,
      description,
      price,
      discount_price,
      number,
      status,
    }
    const setSql = getKeyMapValue(params)
    const sql = `update t_goods set ${setSql}, update_time = now() where id = ${id}`
    query(sql, (err) => {
      if (err) {
        res.fail("修改失败", { data: err })
      } else {
        res.success()
      }
    })
  },
  // 删除商品
  deleteGoods: (req, res) => {
    const body = req.query
    const { id } = body
    const sql = `delete from t_goods where id = ${id}`
    query(sql, (err) => {
      if (err) {
        res.fail("删除失败", { data: err })
      } else {
        res.success()
      }
    })
  },
  // 获取商品列表
  goodsListPage: (req, res) => {
    const body = req.body
    const { name, pageNum, pageSize } = body
    const page = pageLimit(pageNum, pageSize)

    const totalSql = `select * from t_goods where name like '%${name}%'`
    query(totalSql, (terr, tRes) => {
      const searchSql = `select *, date_format(create_time, '${date_type}') create_time, date_format(update_time, '${date_type}') update_time from t_goods where name like '%${name}%' order by create_time desc limit ${page[0]}, ${page[1]}`
      query(searchSql, (err, result) => {
        if (err) {
          res.fail(null, { data: err })
          return
        }
        res.success({
          data: {
            list: result,
            pageNum,
            pageSize,
            total: tRes.length,
          },
        })
      })
    })
  },
}

module.exports = methods
